package com.bee.app.tool;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.TableMapping;

/**
 * SQL生成工具
 * 
 * @author liuzy
 * @version 2015年7月5日
 */
public class SqlBuilder {

	private List<String> modelNames = new ArrayList<>();
	
//	private List<String> joins = new ArrayList<>();

	private List<String> conditions = new ArrayList<>();

	private List<Object> values = new ArrayList<>();

	private StringBuilder sql = new StringBuilder();

	public SqlBuilder model(Model<?> model) {
		modelNames.add(" " + TableMapping.me().getTable(model.getClass()).getName());
		return this;
	}
	
//	public SqlBuilder join(Model<?> model) {
//		modelNames.add(" " + TableMapping.me().getTable(model.getClass()).getName());
//		joins.add(" inner join");
//		return this;
//	}
//	
//	public SqlBuilder leftjoin(Model<?> model) {
//		modelNames.add(" " + TableMapping.me().getTable(model.getClass()).getName());
//		joins.add(" left join");
//		return this;
//	}
//	
//	public SqlBuilder rightjoin(Model<?> model) {
//		modelNames.add(" " + TableMapping.me().getTable(model.getClass()).getName());
//		joins.add(" right join");
//		return this;
//	}

	public SqlBuilder and(String column, Object value) {
		if (value == null)	return this;
		conditions.add(" and " + column + " = ?");
		values.add(value);
		return this;
	}

	public SqlBuilder and(String column, String condition, Object value) {
		if (value == null)	return this;
		conditions.add(" and " + column + " " + condition + " ?");
		values.add(value);
		return this;
	}
	
	public SqlBuilder or(String column, Object value) {
		if (value == null)	return this;
		conditions.add(" or " + column + " = ?");
		values.add(value);
		return this;
	}
	
	public SqlBuilder or(String column, String condition, Object value) {
		if (value == null)	return this;
		conditions.add(" or " + column + " " + condition + " ?");
		values.add(value);
		return this;
	}

	public String sql() {
		// 1.生成select表
		if (modelNames.isEmpty())
			throw new RuntimeException("请先调用model(...)方法");
		sql.append("select * from").append(modelNames.get(0));
//		if (modelNames.size() > 1 ) {
//			for (int i = 0; i < joins.size(); i++) {
//				sql.append(joins.get(i)).append(modelNames.get(i+1));
//			}
//		}
		// 2.生成where条件
		sql.append(" where 1=1");
		for (String condition : conditions) {
			sql.append(condition);
		}
		return sql.toString();
	}

	public Object[] values() {
		return values.toArray();
	}

}
